import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.sql.Connection;

/**
 * Created by wuhainan on 2017/2/21.
 */
public class MyRealm extends AuthorizingRealm {
    private UserDao userDao = new UserDao();
    private DbUtil dbUtil = new DbUtil();

    /**
     * 为当前登录用户授予角色和权限
     *
     * @param principalCollection
     * @return
     */
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principalCollection) {
        String currentUser= (String) principalCollection.getPrimaryPrincipal();
        Connection connection=null;
        SimpleAuthorizationInfo authorizationInfo =new SimpleAuthorizationInfo();
        try {
            connection=dbUtil.getConnection();
            authorizationInfo.setRoles(userDao.getRoles(connection,currentUser));
            authorizationInfo.setStringPermissions(userDao.getPermissions(
                    connection,currentUser));
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                dbUtil.closeConnection(connection);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return authorizationInfo;
    }

    /**
     * 验证当前登录用户
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authenticationToken) throws AuthenticationException {
        String currentUser = (String) authenticationToken.getPrincipal();
        Connection connection = null;
        try {
            connection = dbUtil.getConnection();
            User user = userDao.getByUserName(connection, currentUser);
            if (user != null) {
                AuthenticationInfo authenticationInfo = new
                        SimpleAuthenticationInfo(user.getUserName(),
                        user.getPassword(), this.getName());
                return authenticationInfo;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dbUtil.closeConnection(connection);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
